package com.mc.fastkit.ext

import android.content.res.TypedArray
import android.graphics.Color
import android.util.TypedValue
import androidx.annotation.StyleableRes
import com.google.android.material.shape.AbsoluteCornerSize
import com.google.android.material.shape.CornerSize
import com.google.android.material.shape.RelativeCornerSize
import androidx.core.graphics.toColorInt

fun TypedArray.getColor(@StyleableRes index: Int, defValue: String): Int {
    return getColor(index, defValue.toColorInt())
}

fun TypedArray.getString(@StyleableRes index: Int, defValue: String): String {
    return getString(index) ?: defValue
}

fun TypedArray.getCornerSize(index: Int, defaultValue: CornerSize): CornerSize {
    val value = peekValue(index) ?: return defaultValue
    return when (value.type) {
        TypedValue.TYPE_DIMENSION -> {
            AbsoluteCornerSize(
                TypedValue.complexToDimensionPixelSize(value.data, resources.displayMetrics)
                    .toFloat()
            )
        }

        TypedValue.TYPE_FRACTION -> RelativeCornerSize(value.getFraction(1.0f, 1.0f))

        else -> defaultValue
    }
}